package cn.bonoon.kernel.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;

import org.springframework.web.multipart.MultipartFile;

import cn.bonoon.util.PathUtil;

/**
 * 已经存储的文件信息，这里只能是在本地进行存储的，如果需要远程存储的，则不会返回这个类
 * @author jackson
 *
 */
public class FileInfo extends AbstractBFile{
	
	/** 上传上来的源文件 */
	protected final MultipartFile sourceFile;
	/** 已经保存了的文件 */
	protected final File targetFile;
//	/** 文件保存所在的目录 */
//	protected final File folder;
	
	public static String parseOriginalFilename(MultipartFile sourceFile){
		String originalFilename = sourceFile.getOriginalFilename();
		int lastp = originalFilename.lastIndexOf(PathUtil.separatorChar);
		
		if(lastp >= 0){
			originalFilename = originalFilename.substring(lastp + 1);
		}
		return originalFilename;
	}
	
	public FileInfo(MultipartFile sourceFile, /*File folder,*/ File targetFile, BFile bfile) {
		super(bfile);
		this.sourceFile = sourceFile;
//		this.folder = folder;
		this.targetFile = targetFile;
	}
	
	public InputStream open() throws Exception{
		return new FileInputStream(targetFile);
	}
	
	public File getFile(){
		return targetFile;
	}
	
	public MultipartFile getSourceFile() {
		return sourceFile;
	}
	
	/** 文档的大小 */
	public long getSize() {
		return targetFile.length();
	}

	/** 上传上来的文档的原来的名称 */
	public String getOriginalFilename() {
		return parseOriginalFilename(sourceFile);
	}
	
	public <T extends StoragePersistable> T instance(T target){
		
		target.setPath(internalResolveFilepath(sourcePath));
		target.setFilename(internalResolveFilename());
		target.setPostfix(interanlResolveFilesuffix());
		
		target.setCreateAt(new Date());
		target.setSize(getSize());
		return target;
	}
	
	public <T extends StoragePersistable> T instance(Class<T> target) throws Exception{
		return instance(target.newInstance());
	}
}
